//
//  CZPhotoSelectedController.swift
//  broser
//
//  Created by 李伟鹏 on 16/5/24.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

private let reuseIdentifier = "Cell"

class CZPhotoSelectedController: UICollectionViewController {

    var photos = [UIImage]()
    
     private let MaxImageCount = 6
    
    private let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
    
    init(){
        super.init(collectionViewLayout: layout)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.collectionView!.backgroundColor = UIColor.whiteColor()
        
        self.collectionView!.registerClass(CZPhotoSelectorCell.self, forCellWithReuseIdentifier: reuseIdentifier)
        
        layout.itemSize = CGSize(width: 80, height: 80)
        self.collectionView?.contentInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)

    }
}

extension CZPhotoSelectedController{
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return photos.count < MaxImageCount ? photos.count + 1 : MaxImageCount
    }
    
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! CZPhotoSelectorCell
        cell.backgroundColor = UIColor.brownColor()
        cell.delegate = self
        
        if indexPath.item < photos.count{
            cell.image = photos[indexPath.item]
        }else{
            cell.setupAddButton()
        }
        
        return cell
    }
}

extension CZPhotoSelectedController: CZPhotoSelectorCellDelegate {
    /// 删除按钮被点击
    func photoSelectroCellDidClickDeleteButton(cell: CZPhotoSelectorCell) {
        let indexPath = collectionView!.indexPathForCell(cell)!
        photos.removeAtIndex(indexPath.item)
        collectionView?.reloadData()
        
    }
    
    /// 加好按钮被点击
    func photoSelectorCellDidClickAddButton(cell: CZPhotoSelectorCell) {
        let picker = UIImagePickerController()
        picker.delegate = self
        presentViewController(picker, animated: true, completion: nil)
    }
}

extension CZPhotoSelectedController: UIImagePickerControllerDelegate, UINavigationControllerDelegate{
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        
        let newImage = image.scaleImage(200)
        
        photos.append(newImage)
        collectionView?.reloadData()
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
}
